/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jsrpc.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Hashtable;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jsrpc.bridge.Protocal;
import org.jsrpc.core.Adapter;
import org.jsrpc.core.Remote;
import org.jsrpc.vo.CallMethod;

/**
 *
 * @author neo
 */
public class JsRpcServlet extends HttpServlet {
    Logger log = Logger.getLogger(this.getClass().getName());
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        log.info("Request remote procedure call.");
        response.setContentType("text/plain; charset=UTF-8");
        PrintWriter out = response.getWriter();
        StringBuilder s = new StringBuilder();
        try {
            BufferedReader buf = new BufferedReader(
                    new InputStreamReader(request.getInputStream()));
            String str;
            while( (str=buf.readLine()) != null ) {
                s.append(str);
            }
            buf.close();
            String res = URLDecoder.decode(s.toString(),"UTF-8");
            System.out.println("Response -==["+res+"]==-");
            Protocal protocal = new Protocal();
            log.info("Transfer protocal.");
            Hashtable tables = protocal.getTable(res);
//            for (Enumeration enums = tables.keys(); enums.hasMoreElements(); ) {
//                String key = (String)enums.nextElement();
//                System.out.println("key["+ key+"]value["+ (String)tables.get(key)+"]");
//
//            }
            Adapter adapter = new Adapter();
            log.info("Adapter protocal.");
            CallMethod callMethod = adapter.transformerCallMethod(tables, protocal);
            log.info("Protocal to object.");
            String className = callMethod.getClassName();
            log.info("calling remote.");

            Remote remote = new Remote();
            String returnObject = remote.invoke(className, callMethod, getServletContext(), request);
            //System.out.print("re["+returnObject+"]");
            out.print(returnObject.trim());
            //out.println("OK");
            log.info("Response object.");
        } catch(Exception e) {
            e.printStackTrace();
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
